from fastapi import APIRouter
from pydantic import BaseModel
from intelli_port.model import create_qwen_inferencer
from intelli_port.commons.observability import provider_error_rate, histogram_p95_ms_by_label, provider_request_latency_ms


router = APIRouter()
qwen = create_qwen_inferencer()


class InferRequest(BaseModel):
    text: str
    lang: str = "zh"


@router.post("/infer")
async def infer(req: InferRequest):
    return await qwen.infer_short_text(req.text, req.lang)


@router.get("/health")
async def qwen_health():
    return qwen.stats()


@router.get("/providers")
async def qwen_providers():
    from intelli_port.commons.config import load_settings
    s = load_settings()
    return {"priority": s.qwen_provider_priority.split(",")}


class ProvidersSetRequest(BaseModel):
    priority: list[str]


@router.post("/providers/set")
async def qwen_providers_set(req: ProvidersSetRequest):
    return qwen.set_priority(req.priority)


@router.get("/providers/health")
async def qwen_providers_health():
    metrics = {
        "qwen_http_error_rate": provider_error_rate("qwen_http"),
        "qwen_vllm_error_rate": provider_error_rate("qwen_vllm"),
        "qwen_hybridflow_error_rate": provider_error_rate("qwen_hybridflow"),
        "qwen_http_p95_ms": histogram_p95_ms_by_label(provider_request_latency_ms, "name", "qwen_http"),
        "qwen_vllm_p95_ms": histogram_p95_ms_by_label(provider_request_latency_ms, "name", "qwen_vllm"),
        "qwen_hybridflow_p95_ms": histogram_p95_ms_by_label(provider_request_latency_ms, "name", "qwen_hybridflow"),
    }
    states = qwen.pm.provider_states()
    return {"metrics": metrics, **states}


class ProviderCooldownRequest(BaseModel):
    provider: str
    seconds: float | None = None


@router.post("/providers/cooldown")
async def qwen_provider_cooldown(req: ProviderCooldownRequest):
    return qwen.pm.cooldown(req.provider, req.seconds)


class ProviderResumeRequest(BaseModel):
    provider: str


@router.post("/providers/resume")
async def qwen_provider_resume(req: ProviderResumeRequest):
    return qwen.pm.resume(req.provider)